import type { HttpHandler } from 'msw';
import { setupWorker } from 'msw/browser';

import { handlers } from './login/index';

const mocks = import.meta.glob('../mocks/*/*.ts', { eager: true });

const allMock: HttpHandler[] = [];
for (const path in mocks) {
  const module = mocks[path] as { handlers?: HttpHandler[] };

  // 添加安全检查和日志
  if (module.handlers && Array.isArray(module.handlers)) {
    allMock.push(...module.handlers);
  } else {
    console.warn(`模块 ${path} 没有导出 handlers 或 handlers 不是数组`, module);
  }
}
// console.log(handlers);


export async function enableMocking() {
  if (import.meta.env.DEV) {
    const worker = setupWorker(...handlers);
    await worker.start({
      serviceWorker: {
        url: '/mockServiceWorker.js',
        options: {
          scope: '/',
        },
      },
      onUnhandledRequest: 'bypass',
      quiet: false, // 显示详细日志
      findWorker: (scriptURL) => scriptURL.includes('mockServiceWorker'),
    });
    console.log('msw start');
  }
  return Promise.resolve();
}
